package com.lagou.rpc.consumer.proxy;

import com.alibaba.fastjson.JSON;
import com.lagou.rpc.common.RpcRequest;
import com.lagou.rpc.common.RpcResponse;
import com.lagou.rpc.config.ZookeeperConfig;
import com.lagou.rpc.consumer.client.RpcClient;
import com.lagou.rpc.zk.ZKApi;
import org.apache.curator.framework.CuratorFramework;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 客户端代理类-创建代理对象
 * 1.封装request请求对象
 * 2.创建RpcClient对象
 * 3.发送消息
 * 4.返回结果
 */
public class RpcClientProxy {
    private static List<RpcClient> rpcClients = new ArrayList<>();
    private static CuratorFramework client = ZookeeperConfig.zkClient();

    static {
        List<String> addresses = null;
        try {
            addresses = client.getChildren().forPath("/server");
        } catch (Exception e) {
            e.printStackTrace();
        }
        for (String s: addresses) {
            String[] split = s.split(":");
            String ip = split[0];
            String port = split[1];
            rpcClients.add(new RpcClient(ip, Integer.parseInt(port)));
        }
    }

    private static int requestCount = 0;

    public static Object createProxy(Class serviceClass) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{serviceClass}, new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        //1.封装request请求对象
                        RpcRequest rpcRequest = new RpcRequest();
                        rpcRequest.setRequestId(UUID.randomUUID().toString());
                        rpcRequest.setClassName(method.getDeclaringClass().getName());
                        rpcRequest.setMethodName(method.getName());
                        rpcRequest.setParameterTypes(method.getParameterTypes());
                        rpcRequest.setParameters(args);
                        
                        //2.创建RpcClient对象
                        // RpcClient rpcClient = new RpcClient("127.0.0.1", 8899);
                        RpcClient rpcClient  = null;
                        List<String> childrenNodes = ZKApi.getChildrenNodes("/server");
                        for (String node: childrenNodes) {
                            System.out.println(node);
                        }
                        if (childrenNodes.size() == 0) {
                            throw new Exception("无法获取服务端节点列表");
                        } else if (childrenNodes.size() == 1) {
                            rpcClient = rpcClients.get(0);
                        } else {
                            for (String path: childrenNodes) {
                                String nodeContent = ZKApi.getNodeContent("/server/" + path);
                                if (!"init".equals(nodeContent)) {
                                    if (System.currentTimeMillis() -  Long.parseLong(ZKApi.getNodeContent(path)) > 5000) {
                                        ZKApi.setNodeContent(path, "init");
                                    }
                                }
                            }

                            rpcClient  = RpcClientProxy.getRpcClient(childrenNodes, 0);
                        }
                        System.out.println("本次访问：" + rpcClient.getPort());

                        try {
                            //3.发送消息
                            Object responseMsg = rpcClient.send(JSON.toJSONString(rpcRequest));
                            RpcResponse rpcResponse = JSON.parseObject(responseMsg.toString(), RpcResponse.class);
                            if (rpcResponse.getError() != null) {
                                throw new RuntimeException(rpcResponse.getError());
                            }
                            //4.返回结果
                            Object result = rpcResponse.getResult();
                            return JSON.parseObject(result.toString(), method.getReturnType());
                        } catch (Exception e) {
                            throw e;
                        } finally {
                            rpcClient.close();
                        }

                    }
                });

    }

    public static RpcClient getRpcClient (List<String> childrenNodes, int index) throws Exception {
        String node = childrenNodes.get(index);
        String nodeContent = ZKApi.getNodeContent("/server/" + node);
        RpcClient rpcClient = rpcClients.get(index);
        if ("init".equals(nodeContent)) {
            index = index == 0 ? 1 : 0;
            rpcClient = rpcClients.get(index);
        }
        return rpcClient;
    }

}
